import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { UserInfo, RouteMenu, UserInfoResponse } from '@/api/system/types'
import { login as loginApi, getUserInfo as getUserInfoApi, logout as logoutApi } from '@/api/system/user'
import { usePermissionStore } from './permission'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(localStorage.getItem('token') || '')
  const userInfo = ref<UserInfo | null>(null)
  const roles = ref<string[]>([])
  const permissions = ref<string[]>([])
  const menus = ref<RouteMenu[]>([])

  const login = async (username: string, password: string) => {
    try {
      const res = await loginApi({ username, password })
      token.value = res.data as unknown as string
      localStorage.setItem('token', token.value)
      return res
    } catch (error) {
      return Promise.reject(error)
    }
  }

  const getUserInfo = async () => {
    try {
      const res = await getUserInfoApi()
      const data = res.data
      userInfo.value = data.user
      roles.value = data.roles || []
      permissions.value = data.permissions || []
      menus.value = data.menus || []
      return res
    } catch (error) {
      roles.value = []
      permissions.value = []
      menus.value = []
      return Promise.reject(error)
    }
  }

  const logout = async () => {
    try {
      await logoutApi()
    } catch (error) {
      console.error('Logout failed:', error)
    } finally {
      const permissionStore = usePermissionStore()
      permissionStore.clearRoutes()
      token.value = ''
      userInfo.value = null
      roles.value = []
      permissions.value = []
      menus.value = []
      localStorage.removeItem('token')
    }
  }

  const loginAndInitialize = async (username: string, password: string) => {
    const permissionStore = usePermissionStore()
    try {
      const loginRes = await login(username, password)
      token.value = loginRes.data

      await getUserInfo()
      await permissionStore.generateRoutes()

      return loginRes
    } catch (error) {
      token.value = ''
      permissionStore.clearRoutes()
      throw error
    }
  }

  return {
    token,
    userInfo,
    roles,
    permissions,
    menus,
    login,
    getUserInfo,
    logout,
    loginAndInitialize
  }
}) 